import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_connect/http/src/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:rembercount/controller/countController.dart';
import 'package:rembercount/controller/themeController.dart';

class TransactionDetailsCard extends StatelessWidget {
  final Map<String, dynamic> record;
  final Function(Map<String, dynamic>) onUpdate;
  final CountController countController;
  final ThemeController themeController;

  const TransactionDetailsCard({
    Key? key,
    required this.record,
    required this.onUpdate,
    required this.countController,
    required this.themeController,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final hasStages = record['stages'] != null && record['stagesList'] != null;
    final hasRefundProgress = record['reFundDate'] != null;
    
    // 计算基础内容高度
    double baseHeight = 180.0; // 基础内容高度
    
    // 如果有进度条，增加额外高度
    if (hasRefundProgress) {
      baseHeight += 120.0; // 进度条组件大约需要120像素高度
    }
    
    // 如果有分期，计算分期内容高度
    final contentHeight = hasStages
        ? (record['stagesList'].length * 60.0) + baseHeight // 每个分期项60高度
        : baseHeight;

    return Container(
      constraints: BoxConstraints(
        maxHeight: hasStages
            ? MediaQuery.of(context).size.height * 0.9 // 有分期时最大高度为屏幕的90%
            : hasRefundProgress
                ? MediaQuery.of(context).size.height * 0.6 // 有进度条时最大高度为屏幕的60%
                : MediaQuery.of(context).size.height * 0.4, // 无进度条时最大高度为屏幕的40%
        minHeight: contentHeight, // 最小高度为内容所需高度
      ),
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: const BorderRadius.vertical(
                top: Radius.circular(20),
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, -2),
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '交易详情',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: themeController.themeColor,
                  ),
                ),
                IconButton(
                  onPressed: () => Navigator.pop(context),
                  icon: const Icon(Icons.close),
                ),
              ],
            ),
          ),
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildDetailItemIsNull('分类', 'category'),
                  _buildDetailItemIsNull('金额', 'amount'),
                  _buildDetailItemIsNull('日期', 'date'),
                  _buildDetailItemIsNull('钱包', 'walletAccount'),
                 
                  _buildDetailItem(
                    '类型',
                    record['countType'] == 'zhi' ? '支出' : '收入',
                  ),
                   _buildDetailItemIsNull('每日回本金额', 'reFund'),
                  if (record['reFundDate'] != null) buildRefundDistanceWidget(record),
                  if (hasStages) ...[
                    _buildDetailItem('分期数', '${record['stages']}期'),
                    const SizedBox(height: 16),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text(
                          '分期详情',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Material(
                          color: Colors.transparent,
                          child: InkWell(
                            onTap: () async {
                              try {
                                await countController.finishState(record);
                                Navigator.pop(context);
                                onUpdate(record);
                                Get.snackbar(
                                  '成功',
                                  '已还清所有分期',
                                  backgroundColor: Colors.green.withOpacity(
                                    0.1,
                                  ),
                                  colorText: Colors.green,
                                  duration: const Duration(seconds: 2),
                                );
                              } catch (e) {
                                Get.snackbar(
                                  '错误',
                                  '操作失败: $e',
                                  backgroundColor: Colors.red.withOpacity(0.1),
                                  colorText: Colors.red,
                                  duration: const Duration(seconds: 2),
                                );
                              }
                            },
                            borderRadius: BorderRadius.circular(20),
                            child: Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 8,
                              ),
                              decoration: BoxDecoration(
                                color: Colors.green.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(20),
                                border: Border.all(
                                  color: Colors.green.withOpacity(0.3),
                                  width: 1,
                                ),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.check_circle_outline,
                                    color: Colors.green,
                                    size: 16,
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    '一键还清',
                                    style: TextStyle(
                                      color: Colors.green,
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    ...record['stagesList'].map<Widget>((stage) {
                      final stageDate = DateTime.parse(stage['stage']);
                      final now = DateTime.now();
                      final isOverdue =
                          stageDate.isBefore(now) &&
                          !(stage['isBack'] ?? false);
                      final isCurrent =
                          stageDate.year == now.year &&
                          stageDate.month == now.month;
                      final isPaid = stage['isBack'] ?? false;

                      return Material(
                        color: Colors.transparent,
                        child: InkWell(
                          onTap:
                              isPaid
                                  ? null
                                  : () => _showRepaymentDialog(
                                    context,
                                    record,
                                    stage,
                                  ),
                          child: Container(
                            margin: const EdgeInsets.only(bottom: 8),
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color:
                                  isPaid
                                      ? Colors.green.withOpacity(0.1)
                                      : isOverdue
                                      ? Colors.red.withOpacity(0.1)
                                      : isCurrent
                                      ? themeController.themeColor.withOpacity(
                                        0.1,
                                      )
                                      : Colors.grey[50],
                              borderRadius: BorderRadius.circular(8),
                              border: Border.all(
                                color:
                                    isPaid
                                        ? Colors.green.withOpacity(0.3)
                                        : isOverdue
                                        ? Colors.red.withOpacity(0.3)
                                        : isCurrent
                                        ? themeController.themeColor
                                            .withOpacity(0.3)
                                        : Colors.transparent,
                                width: 1,
                              ),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    if (isPaid)
                                      Icon(
                                        Icons.check_circle,
                                        color: Colors.green,
                                        size: 16,
                                      )
                                    else if (isOverdue)
                                      Icon(
                                        Icons.warning,
                                        color: Colors.red,
                                        size: 16,
                                      )
                                    else if (isCurrent)
                                      Icon(
                                        Icons.access_time,
                                        color: themeController.themeColor,
                                        size: 16,
                                      ),
                                    if (isPaid || isOverdue || isCurrent)
                                      const SizedBox(width: 8),
                                    Text(
                                      stage['stage'],
                                      style: TextStyle(
                                        fontSize: 14,
                                        fontWeight: FontWeight.w500,
                                        color:
                                            isPaid
                                                ? Colors.green
                                                : isOverdue
                                                ? Colors.red
                                                : isCurrent
                                                ? themeController.themeColor
                                                : Colors.black87,
                                      ),
                                    ),
                                  ],
                                ),
                                Row(
                                  children: [
                                    Text(
                                      '¥${stage['amount']}',
                                      style: TextStyle(
                                        fontSize: 14,
                                        fontWeight: FontWeight.bold,
                                        color:
                                            isPaid
                                                ? Colors.green
                                                : isOverdue
                                                ? Colors.red
                                                : isCurrent
                                                ? themeController.themeColor
                                                : Colors.black87,
                                      ),
                                    ),
                                    if (isPaid) const SizedBox(width: 8),
                                    if (isPaid)
                                      Container(
                                        padding: const EdgeInsets.symmetric(
                                          horizontal: 8,
                                          vertical: 2,
                                        ),
                                        decoration: BoxDecoration(
                                          color: Colors.green.withOpacity(0.1),
                                          borderRadius: BorderRadius.circular(
                                            4,
                                          ),
                                        ),
                                        child: Text(
                                          '已还款 ${stage['backTime']}',
                                          style: const TextStyle(
                                            fontSize: 12,
                                            color: Colors.green,
                                          ),
                                        ),
                                      ),
                                    if (isOverdue) const SizedBox(width: 8),
                                    if (isOverdue)
                                      Container(
                                        padding: const EdgeInsets.symmetric(
                                          horizontal: 8,
                                          vertical: 2,
                                        ),
                                        decoration: BoxDecoration(
                                          color: Colors.red.withOpacity(0.1),
                                          borderRadius: BorderRadius.circular(
                                            4,
                                          ),
                                        ),
                                        child: const Text(
                                          '已逾期',
                                          style: TextStyle(
                                            fontSize: 12,
                                            color: Colors.red,
                                          ),
                                        ),
                                      ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  ],
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildRefundDistanceWidget(Map<String, dynamic> record) {
    if (record['reFundDate'] == null) return const SizedBox.shrink();

    try {
      // 1. 解析日期
      DateTime endDate = DateFormat("yyyy-MM-dd HH:mm:ss").parse(record['reFundDate']);
      DateTime now = DateTime.now();
      
      // 2. 计算总天数和剩余天数
      DateTime startDate = DateTime.parse(record['date']); // 使用交易日期作为开始日期
      int totalDays = endDate.difference(startDate).inDays;
      int remainingDays = endDate.difference(now).inDays;
      
      // 确保天数不为负数
      if (remainingDays < 0) remainingDays = 0;
      if (totalDays <= 0) totalDays = 1;
      
      // 计算进度百分比
      double progress = 1.0 - (remainingDays / totalDays);
      if (progress < 0) progress = 0;
      if (progress > 1) progress = 1;

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildDetailItem("回本距离", '${remainingDays.toString()}天'),
          const SizedBox(height: 8),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey[300]!),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '回本进度',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: themeController.themeColor,
                      ),
                    ),
                    Text(
                      '${(progress * 100).toStringAsFixed(1)}%',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: themeController.themeColor,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                LinearProgressIndicator(
                  value: progress,
                  backgroundColor: Colors.grey[300],
                  valueColor: AlwaysStoppedAnimation<Color>(
                    progress >= 1.0 ? Colors.green : themeController.themeColor,
                  ),
                  minHeight: 8,
                ),
                const SizedBox(height: 4),
                Text(
                  '开始时间: ${DateFormat('yyyy-MM-dd').format(startDate)}',
                  style: const TextStyle(fontSize: 12, color: Colors.grey),
                ),
                Text(
                  '目标时间: ${DateFormat('yyyy-MM-dd').format(endDate)}',
                  style: const TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
          ),
        ],
      );
    } catch (e) {
      print('日期解析错误: $e');
      return const SizedBox.shrink();
    }
  }
  Widget _buildDetailItemIsNull(String name, var field){
    if (record[field] != null&&record[field] != ''){
   return _buildDetailItem(name, record[field]);   
    } else{
   return SizedBox();
    }
  }

  Widget _buildDetailItem(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: filterReFundDay(label, value),
      ),
    );
  }

  List<Widget> filterReFundDay(var label, var value) {
    print("vla===>" + value);
    if (label == '每日回本金额') {
      return (value != '¥null')
          ? [
            Text(
              label,
              style: const TextStyle(fontSize: 16, color: Colors.grey),
            ),
            Text(
              value,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
            ),
          ]
          : [];
    } else if (label == '回本距离') {
      // 对于回本距离，我们返回一个空的列表，因为进度条组件会自己处理显示
      return [];
    } else {
      return [
        Text(label, style: const TextStyle(fontSize: 16, color: Colors.grey)),
        Text(
          value,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        ),
      ];
    }
  }

  void _showRepaymentDialog(
    BuildContext context,
    Map<String, dynamic> record,
    Map<String, dynamic> stage,
  ) {
    DateTime selectedDate = DateTime.now();

    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: const Text('选择还款时间'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('分期日期: ${stage['stage']}'),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () async {
                      final DateTime? picked = await showDatePicker(
                        context: context,
                        initialDate: selectedDate,
                        firstDate: DateTime(2000),
                        lastDate: DateTime(2100),
                      );
                      if (picked != null) {
                        setState(() {
                          selectedDate = picked;
                        });
                      }
                    },
                    child: Text(
                      '选择日期: ${selectedDate.toString().split(' ')[0]}',
                    ),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () async {
                    try {
                      // 更新stage数据
                      stage['isBack'] = true;
                      stage['backTime'] = selectedDate.toString().split(' ')[0];

                      // 调用API更新数据
                      var res = await countController.updateStage(
                        record['id'],
                        stage,
                      );

                      if (res['code'] == 200) {
                        Navigator.pop(context); // 关闭日期选择对话框
                        Navigator.pop(context); // 关闭详情对话框
                        onUpdate(record); // 通知父组件更新
                        Get.snackbar(
                          '成功',
                          '还款记录已更新',
                          backgroundColor: Colors.green.withOpacity(0.1),
                          colorText: Colors.green,
                          duration: const Duration(seconds: 2),
                        );
                      } else {
                        Get.snackbar(
                          '失败',
                          res['msg'] ?? '更新失败',
                          backgroundColor: Colors.red.withOpacity(0.1),
                          colorText: Colors.red,
                          duration: const Duration(seconds: 2),
                        );
                      }
                    } catch (e) {
                      Get.snackbar(
                        '错误',
                        '更新失败: $e',
                        backgroundColor: Colors.red.withOpacity(0.1),
                        colorText: Colors.red,
                        duration: const Duration(seconds: 2),
                      );
                    }
                  },
                  child: const Text('确认'),
                ),
              ],
            );
          },
        );
      },
    );
  }
}
